package by.epam.trenings.vkphotorest.app;

import by.epam.trenings.vkphotorest.R;
import by.epam.trenings.vkphotorest.adapters.AlbumAdapter;
import by.epam.trenings.vkphotorest.content.contract.TaskContract;
import by.epam.trenings.vkphotorest.requests.PhotoRequestsBuilder;
import by.epam.trenings.vkphotorest.service.ApplicationService;
import by.epam.trenings.vkphotorest.service.ServiceCallbackListener;
import by.epam.trenings.vkphotorest.service.handlers.BaseHandler;
import by.epam.trenings.vkphotorest.service.handlers.impl.DbInsertHandler;
import by.epam.trenings.vkphotorest.utils.TaskApplication;
import android.os.Bundle;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AlbumsActivity extends FragmentActivity implements
		LoaderManager.LoaderCallbacks<Cursor>, ServiceCallbackListener {

	public static final String EXTRA_ALBUM_ID = "album's id";

	public static final String EXTRA_ALBUM_TITLE = "album's title";

	private ProgressBar mProgressBar;

	private ListView mListView;

	private AlbumAdapter mAlbumAdapter;

	private static final int LOADER_ID = 0;

	private int mRequestId;

	private Boolean mIsOrientationChanged = false;

	private static String EXTRA_IS_ORIENTATION_CHANGED = "mIsOrientationChanged";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_albums);

		mProgressBar = (ProgressBar) findViewById(R.id.albums_activity_progress);
		mProgressBar.setVisibility(View.VISIBLE);
		mListView = (ListView) findViewById(R.id.albums_activity_list);

		if (savedInstanceState != null) {
			mIsOrientationChanged = savedInstanceState
					.getBoolean(EXTRA_IS_ORIENTATION_CHANGED);
		}
		if (mIsOrientationChanged == false) {
			mIsOrientationChanged = true;
			mRequestId = TaskApplication.getServiceHelper().deleteDatabase(
					TaskContract.AlbumsColumns.CONTENT_URI, null, null);
		} else {
			mAlbumAdapter = new AlbumAdapter(AlbumsActivity.this, null);
			mListView.setAdapter(mAlbumAdapter);
			getSupportLoaderManager().initLoader(LOADER_ID, null,
					AlbumsActivity.this);
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(EXTRA_IS_ORIENTATION_CHANGED, mIsOrientationChanged);
		super.onSaveInstanceState(outState);
	}

	protected void onResume() {
		super.onResume();
		TaskApplication.getServiceHelper().addListener(this);
	}

	protected void onPause() {
		super.onPause();
		TaskApplication.getServiceHelper().removeListener(this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {

		return new CursorLoader(this, TaskContract.AlbumsColumns.CONTENT_URI,
				null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> paramLoader, final Cursor cursor) {
		if (paramLoader.getId() == LOADER_ID) {
			if (cursor.getCount() != 0) {

				mListView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent i = new Intent(AlbumsActivity.this,
								PhotoGridActivity.class);
						cursor.moveToPosition(position);
						i.putExtra(
								EXTRA_ALBUM_ID,
								cursor.getString(cursor
										.getColumnIndex(TaskContract.AlbumsColumns.SERVER_ID)));
						i.putExtra(
								EXTRA_ALBUM_TITLE,
								cursor.getString(cursor
										.getColumnIndex(TaskContract.AlbumsColumns.TITLE)));
						startActivity(i);
					}
				});
				mAlbumAdapter.swapCursor(cursor);
			}
			mProgressBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> paramLoader) {
		mAlbumAdapter.swapCursor(null);
	}

	@Override
	public void onServiceCallback(int requestId, Intent requestIntent,
			int resultCode, Bundle data) {

		String action = requestIntent.getAction();
		if (resultCode == BaseHandler.FAILURE_RESPONSE
				&& mRequestId == requestId) {
			mProgressBar.setVisibility(View.GONE);
			Toast.makeText(AlbumsActivity.this,
					data.getString(ApplicationService.ACTION_ON_ERROR),
					Toast.LENGTH_SHORT).show();
		} else if (ApplicationService.ACTION_DELETE.equals(action)
				&& mRequestId == requestId) {
			mRequestId = TaskApplication.getServiceHelper().insertDatabase(
					TaskContract.AlbumsColumns.CONTENT_URI,
					PhotoRequestsBuilder.getAllAlbums());
		} else if (ApplicationService.ACTION_INSERT.equals(action)
				&& mRequestId == requestId) {
			if (data.getInt(DbInsertHandler.EXTRA_CURSOR_COUNT) != 0) {
				mAlbumAdapter = new AlbumAdapter(AlbumsActivity.this, null);
				mListView.setAdapter(mAlbumAdapter);
				getSupportLoaderManager().initLoader(LOADER_ID, null,
						AlbumsActivity.this);
			} else {
				mProgressBar.setVisibility(View.GONE);
				String warning = getResources().getString(
						R.string.activity_albyms_strings_no_albums);
				Toast.makeText(AlbumsActivity.this, warning, Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
}
